import { ApiCode, type ApiResult } from '@/utils/axios/types'
import type { AxiosResponse } from 'axios'
import { onMounted, ref, type Ref } from 'vue'

export function useRequest<T>(
  fetchFn: (params?: any) => Promise<AxiosResponse<ApiResult<T>, any>>,
  options?: {
    lazyLoad?: boolean
    params?: Ref<any>
  }
) {
  const is_loading = ref(false)

  const list = ref<T[]>([]) as Ref<T>

  const getData = () => {
    is_loading.value = true
    fetchFn(options?.params?.value)
      .then((res) => {
        const { code, data } = res.data
        if (code === ApiCode.Success) list.value = data
      })
      .finally(() => {
        is_loading.value = false
      })
  }

  onMounted(() => {
    if (!options?.lazyLoad) getData()
  })

  const reload = () => {
    getData()
  }

  return {
    is_loading,
    list,
    reload
  }
}
